﻿#region File and License Information
/*
<File>
	<License Type="BSD">
		Copyright © 2009 - 2015, Outcoder. All rights reserved.
	
		This file is part of Calcium (http://calciumsdk.net).

		Redistribution and use in source and binary forms, with or without
		modification, are permitted provided that the following conditions are met:
			* Redistributions of source code must retain the above copyright
			  notice, this list of conditions and the following disclaimer.
			* Redistributions in binary form must reproduce the above copyright
			  notice, this list of conditions and the following disclaimer in the
			  documentation and/or other materials provided with the distribution.
			* Neither the name of the <organization> nor the
			  names of its contributors may be used to endorse or promote products
			  derived from this software without specific prior written permission.

		THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
		ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
		WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
		DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
		DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
		(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
		LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
		ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
		(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
		SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
	</License>
	<Owner Name="Daniel Vaughan" Email="danielvaughan@outcoder.com" />
	<CreationDate>2013-03-21 20:07:26Z</CreationDate>
</File>
*/
#endregion

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;

namespace Outcoder.UserOptionsModel
{
	/// <summary>
	/// This class allows you to group a set of options within a single XAML data template.
	/// </summary>
	public class CompositeOption : IUserOption, IUserOptionReaderWriter, IProvider<IUserOptionReaderWriter>
	{

		public CompositeOption(Func<string> titleFunc)
		{
			TitleFunc = ArgumentValidator.AssertNotNull(titleFunc, "titleFunc");
		}

		readonly List<IUserOption> userOptions = new List<IUserOption>();

		public IEnumerable<IUserOption> UserOptions
		{
			get
			{
				return userOptions;
			}
		}

		public void AddOption(IUserOption userOption)
		{
			GetReaderWriter(userOption);
			userOptions.Add(userOption);
		}

		public void RemoveOption(IUserOption userOption)
		{
			userOptions.Remove(userOption);
		}

		public void ClearOptions()
		{
			userOptions.Clear();
		}

		IUserOptionReaderWriter GetReaderWriter(IUserOption userOption)
		{
			var result = userOption.ReaderWriter;
			if (result == null)
			{
				var strategy = Dependency.Resolve<IReaderWriterCreationStrategy, ReaderWriterCreationStrategy>(false);
				result = strategy.Create(userOption);
			}

			return result;
		}

		public Func<string> TitleFunc { get; private set; }

		public string Title
		{
			get
			{
				return TitleFunc();
			}
		}

		string imagePath;

		public string ImagePath
		{
			get
			{
				return imagePath;
			}
			set
			{
				if (imagePath != value)
				{
					imagePath = value;
					OnPropertyChanged();
				}
			}
		}

		/// <summary>
		/// Gets or sets the description func, which is used to retrieve 
		/// a description of the option that may be displayed to the user.
		/// </summary>
		/// <value>
		/// The description func.
		/// </value>
		public Func<string> DescriptionFunc { get; set; }

		public string Description
		{
			get
			{
				return DescriptionFunc != null ? DescriptionFunc() : null;
			}
		}

		public string SettingKey { get; private set; }

		/// <summary>
		/// Gets or sets the template name func, 
		/// which is used to display the option in the option view.
		/// </summary>
		/// <value>
		/// The template name func.
		/// </value>
		public Func<string> TemplateNameFunc { get; set; }

		public string TemplateName
		{
			get
			{
				return TemplateNameFunc != null ? TemplateNameFunc() : null;
			}
		}

		public object DefaultValue { get; private set; }

		public IUserOptionReaderWriter ReaderWriter { get; set; }

		#region IUserOptionReaderWriter implementation

		public IUserOption UserOption
		{
			get
			{
				return this;
			}
		}

		public bool Dirty
		{
			get
			{
				foreach (var userOption in userOptions)
				{
					var readerWriter = userOption.ReaderWriter;
					if (readerWriter != null && readerWriter.Dirty)
					{
						return true;
					}
				}

				return false;
			}
		}

		public async Task<SaveOptionResult> Save()
		{
			SaveOptionResult result = null;

			foreach (var userOption in userOptions)
			{
				var readerWriter = userOption.ReaderWriter;
				if (readerWriter != null)
				{
					result = await readerWriter.Save();
					if (result.ResultValue != SaveOptionResultValue.Success)
					{
						return result;
					}
				}
			}

			return result ?? new SaveOptionResult(SaveOptionResultValue.Success);
		}

		public async Task Refresh(bool reload = false)
		{
			foreach (var userOption in userOptions)
			{
				await userOption.Refresh(reload);
			}

			OnPropertyChanged(string.Empty);
		}

		public Type SettingType
		{
			get
			{
				return null;
			}
		}

		#endregion

		public event PropertyChangedEventHandler PropertyChanged;

		protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
		{
			PropertyChangedEventHandler handler = PropertyChanged;
			if (handler != null)
			{
				handler(this, new PropertyChangedEventArgs(propertyName));
			}
		}

		public IUserOptionReaderWriter ProvidedItem
		{
			get
			{
				return this;
			}
		}
	}
}
